package cn.mifengkong.appcommon.webview.jshandler;

import android.content.Context;

import com.mifengkong.frtools.jsbridge.CallBackFunction;
import com.mifengkong.frtools.jsbridge.JsHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cn.mifengkong.appcommon.constant.DeepLinkForNativeFunctionConstant;
import cn.mifengkong.appcommon.util.DeepLinkForNatvieUrlUtil;
import cn.mifengkong.appcommon.webview.listener.JsBridgeCallBackListener;

/**
 * Created by jiangyongxing on 2017/10/9.
 * 描述：
 */

public class GoNativeHandler implements JsHandler {

    protected Context mContext;
    private String applicationId;
    private JsBridgeCallBackListener listener;
    private String pageName;
    protected String[] nameAndParamters;

    public GoNativeHandler(Context context, String applicationId, JsBridgeCallBackListener listener) {
        this.mContext = context;
        this.applicationId = applicationId;
        this.listener = listener;
    }

    @Override
    public void OnHandler(String handlerName, String responseData, CallBackFunction function) {
        String nativeUrlCode = parseResonseData(responseData);
        if (listener != null) {
            DeepLinkForNatvieUrlUtil.startActivityOrFunction(mContext, nameAndParamters, nativeUrlCode, applicationId, function, listener);
        }
    }

    /**
     * 获取是否需要跳转页面还是需要打开功能
     *
     * @param responseData
     * @return
     */
    String parseResonseData(String responseData) {
        try {
            JSONObject responseDataJO = new JSONObject(responseData);
            pageName = responseDataJO.getString("pageName");
            nameAndParamters = DeepLinkForNatvieUrlUtil.splitNativeUrl(pageName);
            return DeepLinkForNatvieUrlUtil.nativeUrlToActivityOrFunction(pageName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return DeepLinkForNativeFunctionConstant.NATIVE_URL_START_ACTIVITY;
    }

}